<template>
  <div class="property-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <h1>物业系统数据中心</h1>
      </div>
      <div class="date-filter">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
        />
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <div class="stats-cards">
      <div class="stat-card" v-for="(stat, index) in stats" :key="index">
        <div class="stat-info">
          <p class="stat-label">{{ stat.label }}</p>
          <h3 class="stat-value">{{ stat.value }}</h3>
          <p class="stat-change" :class="{ positive: stat.change > 0, negative: stat.change < 0 }">
            <i class="fa fa-arrow-up" v-if="stat.change > 0"></i>
            <i class="fa fa-arrow-down" v-if="stat.change < 0"></i>
            {{ Math.abs(stat.change) }}% {{ stat.change > 0 ? '增长' : '下降' }}
          </p>
        </div>
        <div class="stat-icon" :style="{ backgroundColor: stat.color + '20' }">
          <!-- 若依框架通常使用Font Awesome图标 -->
          <i :class="stat.iconClass" :style="{ color: stat.color }"></i>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 业主增长趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>业主数量增长趋势</h2>
          <el-select v-model="timeRange" @change="handleTimeRangeChange">
            <el-option label="近7天" value="7days"></el-option>
            <el-option label="近30天" value="30days"></el-option>
            <el-option label="近90天" value="90days"></el-option>
            <el-option label="全年" value="year"></el-option>
          </el-select>
        </div>
        <div class="chart-container">
          <div ref="ownerTrendChart" class="chart"></div>
        </div>
      </div>

      <!-- 房屋类型分布 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>房屋类型分布</h2>
        </div>
        <div class="chart-container">
          <div ref="houseTypeChart" class="chart"></div>
        </div>
      </div>

      <!-- 楼宇入住率 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>楼宇入住率</h2>
        </div>
        <div class="chart-container">
          <div ref="buildingOccupancyChart" class="chart"></div>
        </div>
      </div>

      <!-- 投诉与维修统计 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>投诉与维修请求统计</h2>
        </div>
        <div class="chart-container">
          <div ref="complaintRepairChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'PropertyDashboard',
  setup() {
    // 日期范围选择
    const dateRange = ref([]);
    // 时间范围选择
    const timeRange = ref('30days');

    // 关键指标数据：使用若依框架兼容的Font Awesome图标
    const stats = ref([
      {
        label: '总业主数量',
        value: '1,284',
        change: 5,
        iconClass: 'fa fa-users', // 业主图标
        color: '#409eff'
      },
      {
        label: '总房屋数量',
        value: '1,842',
        change: 4,
        iconClass: 'fa fa-home', // 房屋图标
        color: '#67c23a'
      },
      {
        label: '总楼宇数量',
        value: '24',
        change: 0,
        iconClass: 'fa fa-building', // 楼宇图标
        color: '#e6a23c'
      },
      {
        label: '待处理事项',
        value: '18',
        change: -13,
        iconClass: 'fa fa-exclamation-circle', // 待处理事项图标
        color: '#f56c6c'
      }
    ]);

    // 图表引用
    const ownerTrendChart = ref(null);
    const houseTypeChart = ref(null);
    const buildingOccupancyChart = ref(null);
    const complaintRepairChart = ref(null);

    // 生成模拟的日期数据
    const generateDates = (days) => {
      const dates = [];
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
      }
      return dates;
    };

    // 业主增长趋势数据
    const getOwnerTrendData = (range) => {
      let days = 30;
      switch(range) {
        case '7days': days = 7; break;
        case '90days': days = 90; break;
        case 'year': days = 365; break;
        default: days = 30;
      }

      const dates = generateDates(days);
      const base = 1000;
      const data = dates.map(() => Math.floor(base + Math.random() * 300));

      // 确保数据呈增长趋势
      for (let i = 1; i < data.length; i++) {
        data[i] = Math.max(data[i], Math.floor(data[i-1] - 50 + Math.random() * 100));
      }

      return { dates, data };
    };

    // 房屋类型分布数据
    const houseTypeData = ref({
      types: ['一居室', '二居室', '三居室', '四居室', '复式', '别墅'],
      counts: [320, 580, 650, 180, 75, 37]
    });

    // 楼宇入住率数据
    const buildingOccupancyData = ref({
      buildings: ['1号楼', '2号楼', '3号楼', '4号楼', '5号楼', '6号楼', '7号楼', '8号楼'],
      occupancy: [85, 92, 78, 95, 65, 88, 90, 76]
    });

    // 投诉与维修统计数据
    const complaintRepairData = ref({
      categories: ['水电维修', '卫生清洁', '安全问题', '噪音投诉', '绿化维护', '其他问题'],
      complaints: [45, 28, 15, 32, 10, 8],
      repairs: [62, 12, 5, 8, 18, 4]
    });

    // 初始化业主增长趋势图表
    const initOwnerTrendChart = (range = '30days') => {
      const chart = echarts.init(ownerTrendChart.value);
      const { dates, data } = getOwnerTrendData(range);

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: { color: '#333' },
          formatter: (params) => `${params[0].name}: ${Math.round(params[0].value)} 位业主`
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#eee'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            interval: range === 'year' ? 30 : 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          },
          axisLabel: {
            formatter: (value) => Math.round(value)
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409eff'
            },
            itemStyle: {
              color: '#409eff',
              borderWidth: 2,
              borderColor: '#fff',
              shadowBlur: 4,
              shadowColor: 'rgba(0, 0, 0, 0.1)'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0)' }
              ])
            }
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 初始化房屋类型分布图表
    const initHouseTypeChart = () => {
      const chart = echarts.init(houseTypeChart.value);

      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: { color: '#333' },
          formatter: (params) => `${params.seriesName} <br/>${params.name}: ${Math.round(params.value)} 套 (${params.percent.toFixed(1)}%)`
        },
        legend: {
          orient: 'vertical',
          left: 10,
          textStyle: {
            color: '#666'
          }
        },
        series: [
          {
            name: '房屋类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: houseTypeData.value.types.map((type, index) => ({
              name: type,
              value: houseTypeData.value.counts[index]
            }))
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 初始化楼宇入住率图表
    const initBuildingOccupancyChart = () => {
      const chart = echarts.init(buildingOccupancyChart.value);

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: { color: '#333' },
          formatter: (params) => `${params[0].name}: ${Math.round(params[0].value)}%`
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: buildingOccupancyData.value.buildings,
          axisLine: {
            lineStyle: {
              color: '#eee'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          },
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '入住率',
            type: 'bar',
            data: buildingOccupancyData.value.occupancy,
            itemStyle: {
              color: function(params) {
                const colorList = ['#67c23a', '#52c41a', '#7cb305', '#a0d995', '#fadb14', '#fa8c16', '#f56c6c', '#e74c3c'];
                return colorList[params.dataIndex];
              },
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              formatter: (params) => `${Math.round(params.value)}%`
            }
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 初始化投诉与维修统计图表
    const initComplaintRepairChart = () => {
      const chart = echarts.init(complaintRepairChart.value);

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: { color: '#333' },
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            let res = `${params[0].name}<br/>`;
            params.forEach(item => {
              res += `${item.seriesName}: ${Math.round(item.value)} 条<br/>`;
            });
            return res;
          }
        },
        legend: {
          data: ['投诉', '维修请求'],
          textStyle: {
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: complaintRepairData.value.categories,
          axisLine: {
            lineStyle: {
              color: '#eee'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          },
          axisLabel: {
            formatter: (value) => Math.round(value)
          }
        },
        series: [
          {
            name: '投诉',
            type: 'bar',
            data: complaintRepairData.value.complaints,
            itemStyle: {
              color: '#f56c6c',
              borderRadius: [4, 4, 0, 0]
            }
          },
          {
            name: '维修请求',
            type: 'bar',
            data: complaintRepairData.value.repairs,
            itemStyle: {
              color: '#409eff',
              borderRadius: [4, 4, 0, 0]
            }
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 日期范围变化处理
    const handleDateChange = (val) => {
      console.log('日期范围变化:', val);
      // 实际项目中可根据日期范围重新加载数据
    };

    // 时间范围变化处理
    const handleTimeRangeChange = (val) => {
      timeRange.value = val;
      initOwnerTrendChart(val);
    };

    // 监听时间范围变化
    watch(timeRange, (newVal) => {
      initOwnerTrendChart(newVal);
    });

    // 页面加载时初始化图表
    onMounted(() => {
      // 确保DOM元素已加载
      setTimeout(() => {
        initOwnerTrendChart();
        initHouseTypeChart();
        initBuildingOccupancyChart();
        initComplaintRepairChart();
      }, 0);
    });

    return {
      dateRange,
      timeRange,
      stats,
      ownerTrendChart,
      houseTypeChart,
      buildingOccupancyChart,
      complaintRepairChart,
      handleDateChange,
      handleTimeRangeChange
    };
  }
};
</script>

<style scoped>
.property-dashboard {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 30px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.page-title h1 {
  font-size: 18px;
  color: #1f2d3d;
  margin: 0;
  font-weight: 600;
}

.date-filter {
  width: 340px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-card:nth-child(1) {
  border-left-color: #409eff;
}

.stat-card:nth-child(2) {
  border-left-color: #67c23a;
}

.stat-card:nth-child(3) {
  border-left-color: #e6a23c;
}

.stat-card:nth-child(4) {
  border-left-color: #f56c6c;
}

.stat-info .stat-label {
  color: #86909c;
  margin: 0 0 5px 0;
  font-size: 13px;
}

.stat-info .stat-value {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 3px 0;
  color: #1f2d3d;
}

.stat-info .stat-change {
  margin: 0;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.stat-change.positive {
  color: #67c23a;
}

.stat-change.negative {
  color: #f56c6c;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
  gap: 15px;
}

.chart-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.chart-header {
  padding: 12px 15px;
  border-bottom: 1px solid #f2f3f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h2 {
  margin: 0;
  font-size: 14px;
  color: #1f2d3d;
  font-weight: 600;
}

.chart-container {
  padding: 15px;
}

.chart {
  width: 100%;
  height: 300px;
}

/* 响应式调整 - 适配若依框架常用分辨率 */
@media (max-width: 1024px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .date-filter {
    width: 100%;
  }

  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }

  .chart {
    height: 260px;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }

  .chart {
    height: 220px;
  }
}
</style>
